import socket
import time
from multiprocessing import Process
import logging,json

# 目标地址39.106.34.123:12347
TARGET_HOST = '39.106.34.123'
TARGET_PORT = 12347

# 每个进程发送的消息数量
MESSAGES_PER_PROCESS = 100000 // 6

class socketclient:
    def send_requests(self, count, start_index):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.connect((TARGET_HOST, TARGET_PORT))
            for i in range(start_index, start_index + count):
                # message = f"Message {i}\n".encode('utf-8')
                message = bytes([10])+json.dumps({"topic":"test/#","info":{"id":(1,i,3),"data":{i:i}}}).encode('utf-8')
   
                sock.sendall(message)
                response = sock.recv(100)
                # if i % 1000 == 0:
                #     print(f"Sent request {i + start_index}")

def send_requests_thread(count, start_index):
    socketclient().send_requests(count, start_index)

def send_requests_process(count, start_index):
    process = Process(target=send_requests_thread, args=(count, start_index))
    process.start()
    process.join()

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

    t = time.time()
    
    processes = []
    total_messages = 100000
    
    for i in range(6):
        p = Process(target=send_requests_process, args=(MESSAGES_PER_PROCESS, i * MESSAGES_PER_PROCESS))
        processes.append(p)
        p.start()

    for p in processes:
        p.join()

    elapsed_time = time.time() - t
    logging.info(f"Total time taken: {elapsed_time:.2f} seconds")